<template>
  <div>
    <div v-for="(group, index) in selectedNode.props.groups" :key="index + '_g'" class="group">
      <div class="group-header">
        <span class="group-name">条件组 {{ groupNames[index] }}</span>
        <div class="group-cp">
          <span>组内条件关系：</span>
          <el-switch v-model="group.groupType" active-color="#409EFF"
                     inactive-color="#c1c1c1" active-value="AND" inactive-value="OR"
                     active-text="且" inactive-text="或"/>
        </div>
        <div class="group-operation">
          <el-popover placement="bottom" title="选择审批条件" width="300" trigger="click">
            <!-- <div>以下条件将决定具体的审批流程</div>-->
            <el-checkbox-group v-model="group.cids" value-key="id">
              <el-checkbox :label="condition.id" v-for="(condition, cindex) in conditionList" :key="condition.id" @change="conditionChange(cindex, group)">
                {{ condition.title }}
              </el-checkbox>
            </el-checkbox-group>
            <i class="el-icon-plus" slot="reference"></i>
          </el-popover>
          <i class="el-icon-delete" @click="delGroup(index)"></i>
        </div>
      </div>
      <div class="group-content">
        <p v-if="group.conditions.length === 0">点击右上角 + 为本条件组添加条件 ☝</p>
        <div v-else>
          <el-form ref="condition-form" label-width="100px">
            <!--构建表达式-->
            <el-form-item  v-for="(condition, cindex) in group.conditions" :key="condition.id + '_' + cindex" >
              <ellipsis slot="label" hover-tip :content="condition.title"/>
              <!-- 判断条件是字符串 -->
               <span v-if="condition.valueType === ValueType.string">
               <!-- <el-select size="small" placeholder="判断符" style="width: 120px;" v-model="condition.compare" @change="condition.value = {text:null,value:null}"> -->
                <el-select size="small" placeholder="判断符" style="width: 120px;" v-model="condition.compare" @change="condition.value = ''">
                  <el-option label="等于" value="="></el-option>
                  <el-option label="包含在" value="IN"></el-option>
                </el-select>
                 <!-- 如果是下拉框类型  需要区分等于(单选) 包含(多选)-->
                 <span v-if="isSelect(condition.id)" style="margin-left: 10px">
                  <!-- =等于 -->
                   <div v-if="condition.compare === '='" style="width: 280px;display: inline-block;" >
                    <span v-if="condition.compare && condition.selectItemConfig">
                      <span v-if="condition.selectItemConfig.dictTable">
                       <!-- 单选下拉搜索组件 -->
                      <single-search-select-picker  mode="" :key="condition.id"
                      :readerMode="condition.selectItemConfig.readerMode"
                      :dictTable="condition.selectItemConfig.dictTable" :dicCode="condition.selectItemConfig.dicCode" :dicText="condition.selectItemConfig.dicText" 
                      :isInitLoad="condition.selectItemConfig.isInitLoad"
                      :condition="condition.selectItemConfig.condition"
                      v-model="condition.value"
                      @changeOk="(e) => condition.dictText = e.text"
                      ></single-search-select-picker>
                    </span>
                    <span v-else> 
                      <single-select-picker mode="" :key="condition.id"
                      :readerMode="condition.selectItemConfig.readerMode"
                      :dicCode="condition.selectItemConfig.dicCode" 
                      :isInitLoad="condition.selectItemConfig.isInitLoad"
                      v-model="condition.value"
                      @changeOk="(e) => condition.dictText = e.text"
                      ></single-select-picker>
                    </span>
                      </span>
                  </div> 
                  <!-- 包含 -->
                  <div v-else style="width: 280px;display: inline-block;">
                    <span v-if="condition.compare && condition.selectItemConfig">
                      <span v-if="condition.selectItemConfig.dictTable">
                      <multi-search-select-picker mode="" :key="condition.id"
                       :readerMode="condition.selectItemConfig.readerMode"
                       :dictTable="condition.selectItemConfig.dictTable" :dicCode="condition.selectItemConfig.dicCode" :dicText="condition.selectItemConfig.dicText" 
                       :isInitLoad="condition.selectItemConfig.isInitLoad"
                       :condition="condition.selectItemConfig.condition"
                       v-model="condition.value"
                       @changeOk="(e) => condition.dictText = e.text"
                      ></multi-search-select-picker>
                      </span>
                      <span v-else>
                        <multi-select-picker mode="" :key="condition.id"
                         :readerMode="condition.selectItemConfig.readerMode"
                         :dicCode="condition.selectItemConfig.dicCode" 
                         :isInitLoad="condition.selectItemConfig.isInitLoad"
                         v-model="condition.value"
                         @changeOk="(e) => condition.dictText = e.text"
                        ></multi-select-picker>
                      </span>
                    </span>
                  </div>
                 </span>
                 <span v-else style="margin-left: 10px">
                    <!-- 字符串文本类型 暂时不用处理-->
                   <el-input v-if="condition.compare === '='" style="width: 280px;" placeholder="输入比较值" size="small" v-model="condition.value"/>
                   <el-select v-else style="width: 280px;" multiple clearable filterable allow-create size="small" v-model="condition.value" placeholder="输入可能包含的值"></el-select>
                 </span>
              </span>
              <span v-else-if="condition.valueType === ValueType.number">
                <el-select size="small" placeholder="判断符" style="width: 120px;" v-model="condition.compare">
                  <el-option :label="exp.label" :value="exp.value" :key="exp.value" v-for="exp in explains"></el-option>
                </el-select>
              <span style="margin-left: 10px">
          <!--      <span>{{conditionValType(condition.compare) === 0}} </span> -->
                <el-input style="width: 280px;" v-if="conditionValType(condition.compare) === 0" size="small" placeholder="输入比较值" type="number" v-model="condition.value"/>  
               <el-select style="width: 280px;" multiple filterable allow-create v-else-if="conditionValType(condition.compare) === 1" size="small" v-model="condition.sectionValue" placeholder="输入可能包含的值" @change="(e) => includeChange(e,index,cindex)"></el-select> 
                <span v-else>
                  <el-input style="width: 130px;" size="small" placeholder="输入比较值" v-model="condition.sectionValue[0]" type="number" @input="(e) => numberChange1(e,index,cindex)"/>
                  <span> ~   
                    <el-input size="small" style="width: 130px;" placeholder="输入比较值" v-model="condition.sectionValue[1]" type="number" @input="(e) => numberChange2(e,index,cindex)" />
                  </span>
                </span> 
              </span>
              </span>
              <!--  选择用户 -->
              <span v-else-if="condition.valueType === ValueType.user">
               <!-- <div class="item-desc" style="margin-right: 20px">属于某部门 / 为某些人其中之一</div> -->
                <div>     
                  <user-search-select-picker ref="userRef" v-model="condition.value" 
                  placeholder="请选择用户" mode=""></user-search-select-picker>
                </div>
              </span>  
              <span v-else-if="condition.valueType === ValueType.dept">  
                <j-select-depart v-model="condition.value" :trigger-change="true"
                customReturnField="orgCode" :multi="true"
                :backDepart="true"
                @back="(e) => condition.dictText = getDictText(e)"
                style="width: 90%"
                ></j-select-depart>
              </span> 
              <span v-else-if="condition.valueType === ValueType.date"></span>
              <i class="el-icon-delete" @click="rmSubCondition(group, cindex)"></i>
            </el-form-item>
          </el-form>
        </div>
      </div>
    </div>
   <!-- <org-picker :type="orgType" multiple ref="orgPicker" :selected="users" @ok="selected"></org-picker> -->
  </div>
</template>

<script>
// import OrgPicker from "@/components/wflow/OrgPicker";
// import OrgItems from '../OrgItems'
import {ValueType} from '@/views/wflowable/common/form/ComponentsConfigExport'
import Ellipsis from '@/components/wflow/Ellipsis' 
import {getAction} from '@/api/manage'
import SingleSearchSelectPicker from '@/views/wflowable/common/form/components/SingleSearchSelectPicker'
import MultiSearchSelectPicker from '@/views/wflowable/common/form/components/MultiSearchSelectPicker'
import SingleSelectPicker from '@/views/wflowable/common/form/components/SingleSelectPicker'
import MultiSelectPicker from '@/views/wflowable/common/form/components/MultiSelectPicker'   
import UserSearchSelectPicker from '@/views/wflowable/common/form/components/UserSearchSelectPicker'   
export default {
  name: "ConditionGroupItemConfig",
  components: {Ellipsis,SingleSearchSelectPicker,MultiSearchSelectPicker,SingleSelectPicker,MultiSelectPicker,UserSearchSelectPicker},
  data() {
    return {
      ValueType,
      users: [],
      orgType: 'user',
      showOrgSelect: false,
      //groupConditions: [],
      groupNames: ['A', 'B', 'C', 'D', 'E', 'F', 'G', 'H', 'I', 'J'],
      supportTypes:[ValueType.number, ValueType.string, ValueType.date, ValueType.dept, ValueType.user],
      explains:[
        {label: '等于', value:'='},
        {label: '大于', value:'>'},
        {label: '大于等于', value:'>='},
        {label: '小于', value:'<'},
        {label: '小于等于', value:'<='},
        {label: '包含在', value:'IN'},
        {label: 'x < 值 < x', value:'B'},
        {label: 'x ≤ 值 < x', value:'AB'},
        {label: 'x < 值 ≤ x', value:'BA'},
        {label: 'x ≤ 值 ≤ x', value:'ABA'},
      ],
      dictOptions:[],   //下拉框数据源
      mode:null,
      selectModel:{
        readerMode:false,
        isInitLoad:true,
      },
      userOptions:[],  //用户数据源
      loading:false,
      departValue:'',  //部门
      // sectionValue:[0,0],   //区间值
    }
  },
  computed: {
    selectedNode() {
      // let selectedNodes = this.$store.state.wflow.selectedNode
      // if(selectedNodes.props.groups && selectedNodes.props.groups.length > 0){
      //   selectedNodes.props.groups.map((item)=>{
      //     if(item.conditions && item.conditions.length > 0){
      //       item.conditions.map((item2)=>{
      //         if(item2.valueType === 'Number' && (item2.compare === 'B' || item2.compare === 'AB' || item2.compare === 'BA' || item2.compare === 'ABA')){
      //           item2.sectionValue = item2.sectionValue ? item2.sectionValue.split(',') : [0,0]
      //         }
      //       })
      //     }
      //   })
      // }
      return this.$store.state.wflow.selectedNode
    
    },
    select() {
      return this.selectedNode.props.assignedUser || ''
    },
    formItems(){
      return this.$store.state.wflow.design.formItems
    },
    formMap(){
      const map = new Map();
      this.formItems.forEach(item => this.itemToMap(map, item))
      return map
    },
    conditionList() {
      //构造可用条件选项
      const conditionItems = []
      this.formItems.forEach(item => this.filterCondition(item, conditionItems))
      if (conditionItems.length === 0 || conditionItems[0].id !== 'root'){
        conditionItems.unshift({id: 'root', title: '发起人', valueType: 'User'})
      }
      return conditionItems
    },
  },
  methods: {
    itemToMap(map, item){
      map.set(item.id, item)
      if (item.name === 'SpanLayout'){
        item.props.items.forEach(sub => this.itemToMap(map, sub))
      }
    },
    isSelect(formId){
      let form = this.formMap.get(formId)
      if(form && (form.name === 'SingleSearchSelectPicker' || form.name === 'SingleSelectPicker' || form.name === 'MultiSearchSelectPicker' || form.name === 'MultiSelectPicker')){
        return true
      }
      return false
    },
    getOptions(formId){
      return this.formMap.get(formId).props.options || []
    },
    conditionValType(type){
      switch (type){
        case '=':
        case '>':
        case '>=':
        case '<':
        case '<=': return 0;
        case 'IN': return 1;
        default: return 2;
      }
    },
    selectUser(value, orgType) {
      this.orgType = orgType
      this.users = value
      this.$refs.orgPicker.show()
    },
    filterCondition(item, list){
      if (item.name === 'SpanLayout'){
        item.props.items.forEach(sub => this.filterCondition(sub, list))
      }else if (this.supportTypes.indexOf(item.valueType) > -1 && item.props.required){
        list.push({title: item.title, id: item.id, valueType: item.valueType})
      }
    },
    selected(select) {
      console.log(select)
      this.users.length = 0
      select.forEach(u => this.users.push(u))
    },
    delGroup(index) {
      this.selectedNode.props.groups.splice(index, 1)
    },
    rmSubCondition(group, index){
      group.cids.splice(index, 1)
      group.conditions.splice(index, 1)
    },
    conditionChange(index, group) {
      //判断新增的
      group.cids.forEach(cid => {
        if (0 > group.conditions.findIndex(cd => cd.id === cid)){
          //新增条件
          let condition = {...this.conditionList[index]}
          condition.compare = '';
          // condition.value = []
          condition.value = ''
          condition.dictText = ''
          condition.selectItemConfig={}
          condition.sectionValue = []
          if(group.groupType === 'OR' || group.groupType === 'AND'){
            const formItems = this.formItems
            let formItemsProps = formItems.find((s)=>s.id === condition.id)   
            if(formItemsProps && formItemsProps.props){
               let selectItem = formItemsProps.props
              selectItem.readerMode = false
              selectItem.isInitLoad = true
              condition.selectItemConfig = selectItem
            }else{
              condition.selectItemConfig = {}
            }
          }    
          group.conditions.push(condition)
        }
      })
      for (let i = 0; i < group.conditions.length; i++) {
        //去除没有选中的
        if (group.cids.indexOf(group.conditions[i].id) < 0){
          group.conditions.splice(i, 1)
        }
      }
    },
    //获取部门选择值对应的翻译
    getDictText(info){
      if(info && info.length >0){
       let dictStr=[]
        info.forEach((item)=>{
          dictStr.push(item.text)
        })
        return dictStr.join(',')
      }else{
        return ''
      }
    },
    //选择部门
    departChange(value,index,cindex){
       let conditions = this.selectedNode.props.groups[index].conditions[cindex]
      if(value){
       conditions.value = value.split(',')
      }else{
        conditions.value = []
      }
    },
    //数字区间输入
    numberChange1(value,index,cindex){ 
       let conditions = this.selectedNode.props.groups[index].conditions[cindex]
       if(conditions.sectionValue && conditions.sectionValue.length>0){
         conditions.value = conditions.sectionValue.join(',')
       }
    },
    numberChange2(value,index,cindex){
       let conditions = this.selectedNode.props.groups[index].conditions[cindex]
       if(conditions.sectionValue && conditions.sectionValue.length>0){
         conditions.value = conditions.sectionValue.join(',')
       }
    },
    //number类型包含
    includeChange(value,index,cindex){
      let conditions = this.selectedNode.props.groups[index].conditions[cindex]
      if(conditions.sectionValue && conditions.sectionValue.length>0){
        conditions.value = conditions.sectionValue.join(',')
      }
    },
    
   //模糊查询用户
   remoteMethod(value){
     this.userOptions = []
     if(value){
     this.loading = true
     const apiUrl ='/sys/dict/loadDict/sys_user,username,username' 
     getAction(apiUrl, {
       keyword:value,
       pageSize:20
     }).then(res => {    
       if (res.success) {
         this.userOptions = res.result
       } else {
         this.$message.warning(res.message)
       }
     }).finally(() => {
       this.loading = false
     })
     }else{
        this.userOptions = []
     }
   },

   

  }
}
</script>

<style lang="less" scoped>
.group {
  margin-bottom: 20px;
  color: #5e5e5e;
  overflow: hidden;
  border-radius: 6px;
  border: 1px solid #e3e3e3;

  .group-header {
    padding: 5px 10px;
    background: #e3e3e3;
    position: relative;

    div {
      display: inline-block;
    }

    .group-name {
      font-size: small;
    }

    .group-cp {
      font-size: small;
      position: absolute;
      left: 100px;
      display: flex;
      top: 5px;
      justify-content: center;
      align-items: center;
    }

    .group-operation {
      position: absolute;
      right: 10px;

      i {
        padding: 0 10px;

        &:hover {
          cursor: pointer;
        }
      }
    }
  }

  .group-content{
    padding: 10px 5px;
    p{
      text-align: center;
      font-size: small;
    }
    .el-icon-delete{
      position: absolute;
      cursor: pointer;
      top: 12px;
      right: 0;
    }
  }

  .condition-title{
    display: block;
    width: 100px;
  }
}
</style>
